package org.jeecg.feishu.api.utils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class NotifyDataDecrypter {

    public static byte[] decrypterKey(String keyStr) {
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            // won't happen
        }
        return digest.digest(keyStr.getBytes(StandardCharsets.UTF_8));
    }


    /**
     *
     * @param key 飞书应用配置的 Encrypt Key
     * @param content 请求json encrypt的对应的值
     * @return
     */
    public static String decrypt(String key, String content)  {

        byte[] decode = Base64.getDecoder().decode(content);

        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("AES/CBC/NOPADDING");
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            e.printStackTrace();
        }

        byte[] iv = new byte[16];
        System.arraycopy(decode, 0, iv, 0, 16);

        byte[] data = new byte[decode.length - 16];
        System.arraycopy(decode, 16, data, 0, data.length);

        try {
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decrypterKey(key), "AES"), new IvParameterSpec(iv));
        } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }

        byte[] r = new byte[0];
        try {
            r = cipher.doFinal(data);
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }
        if (r.length > 0) {
            int p = r.length - 1;
            for (; p >= 0 && r[p] < 16; p--) {
            }

            if (p != r.length - 1) {
                byte[] rr = new byte[p + 1];
                System.arraycopy(r, 0, rr, 0, p + 1);
                r = rr;
            }
        }

        String str = new String(r, StandardCharsets.UTF_8);

        System.out.println(str);

        return new String(r, StandardCharsets.UTF_8);
    }


    public static void main(String[]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